<template>
  <cus-form ref="formRef" :nodes="nodes" width="420px" />
</template>

<script lang="ts">
import { ref } from 'vue'
import { useStore } from 'vuex';
import $ from '$';
import { ElMessage } from 'element-plus';

export default {
  props: {
    data: {
      type: Object as any,
      required: true
    }
  },
  setup(props) {
    const areaData = [[], [], []]
    let store = useStore();
    let userId = store.getters.userInfo.user.id;

    let formRef = ref();

    let nodes = ref<any[]>([
      {
        label: '试卷名称',
        key: 'title',
        type: 'input',
        rule: { required: true, message: "请输入试卷名称" },
        default: props.data.title
      },
      {
        label: "学科",
        key: "subjectId",
        type: "cascader",
        url: "/permission/user/userDataSubjects",
        params: { userId },
        default: props.data.subjectId,
        rule: { required: true, message: "请选择学科" },
        valueKey: 'code',
        change: (v) => subjectChange(v)
      },
      {
        label: "年级",
        key: "gradeId",
        type: "select",
        options: [],
        default: props.data.gradeId,
        rule: { required: true, message: "请选择年级" },
      },
      {
        label: "年份",
        key: "year",
        type: "select",
        options: [],
        default: props.data.year,
        rule: { required: true, message: "请选择年份" },
      },
      {
        label: '省市区',
        key: 'provinceCity',
        type: 'cascader',
        lazy: true,
        labelKey: 'name',
        valueKey: 'id',
        checkStrictly: true,
        default: [props.data.provinceId, props.data.cityId, props.data.county].filter(Boolean),
        lazyLoad: ({ data }, resolve) => {
          $.http.post('/system/area/queryByParentId', { parentId: data.id ? data.id : null }).then(res => {
            if (!data.id) areaData[0] = res.json;
            else if (res.json.every(i => i.leaf)) areaData[2] = res.json;
            else areaData[1] = res.json;
            resolve(res.json);
          })
        },
        change: (e) => {
          $.http.post('/admin/publicSchool/queryAll', { provinceId: e[0], cityId: e[1], areaId: e[2] }).then(res => {
            let names = e.map((i, idx) => (areaData[idx].find((j: any) => j.id === i) as any).name);
            [formRef.value.formGroup.provinceName, formRef.value.formGroup.cityName, formRef.value.formGroup.countyName = null] = names;
            [formRef.value.formGroup.provinceId, formRef.value.formGroup.cityId, formRef.value.formGroup.county = null] = e;
            nodes.value[5].options = res.json;
            formRef.value.formGroup.schoolId && (formRef.value.formGroup.schoolId = null);
          })
        }
      },
      {
        label: '公立校',
        key: 'schoolId',
        type: 'select',
        labelKey: 'name',
        valueKey: 'id',
        default: props.data.schoolId,
        options: []
      },
      {
        label: "来源",
        key: "source",
        type: "select",
        options: [],
        default: props.data.source,
        rule: { required: true, message: "请选择来源" },
      },
      {
        key: 'id',
        type: 'hidden',
        default: props.data.id
      }
    ]);
    $.http.post('/system/dictionary/queryDictByCodes', { typeCodesStr: 'QUES_SOURCE' }).then(res => nodes.value[6].options = res.json['QUES_SOURCE']);
    if (props.data.schoolId || [props.data.provinceId, props.data.cityId, props.data.county].filter(Boolean).length) {
      $.http.post('/admin/publicSchool/queryAll', { provinceId: props.data.provinceId, cityId: props.data.cityId, areaId: props.data.county }).then(res => nodes.value[5].options = res.json)
    }
    const subjectChange = (v, isInit?) => {
      $.http.post('/permission/user/userDataRules', { userId, subjectCode: v }).then((res: any) => {
        nodes.value[2].options = res.json.grades;
        nodes.value[3].options = res.json.years;
        if (!isInit) {
          formRef.value.formGroup.gradeId = null;
          formRef.value.formGroup.year = null;
          setTimeout(() => formRef.value.formRef.clearValidate() );
        }
      })
    }
    subjectChange(props.data.subjectId, true);

    const save = (resolve, reject) => {
      formRef.value.validate(async valid => {
        if (valid) {
          valid.subjectId = Array.isArray(valid.subjectId) ? valid.subjectId[1] : valid.subjectId;
          const res = await $.http.json('/tiku/paper/updatePaper', valid);
          if (res.result) {
            ElMessage.success('修改试卷成功~！');
            resolve(res)
          } else {
            ElMessage.warning('修改试卷失败！');
            reject();
          }
        } else {
          reject();
        }
      })
    }

    return { formRef, nodes, save }
  }
}
</script>

<style lang="scss" scoped>

</style>
